<template>
  <div class="addInviteConfig">
    <h2 class="editPage">{{ id ? "修改" : "新增" }}</h2>
    <a-card>
      <a-form :form="form">
        <a-form-item
            label="类目图标"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }"
        >
          <a-upload
              name="file"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :action="prefix+'shop/upload/uploadImage/CATEGORY'"
              :headers="{'Authorization': token}"
              :before-upload="beforeUpload"
              @change="handleChange"
          >
            <img v-if="postUserData.categoryImage" :src="imgUrl+postUserData.categoryImage" alt="avatar"/>
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'"/>
              <div class="ant-upload-text">Upload</div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item
            label="类目名称"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }"
        >
          <a-input
              placeholder="请输入类目名称"
              @change="categoryNameChange"
              v-decorator="[
              'categoryName',
              {
                rules: [{ required: true, message: '请输入类目名称' }],
              },
            ]"
          ></a-input>
        </a-form-item>
        <a-form-item
            label="排序"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 16 }"
        >
          <a-input
              placeholder="请输入排序"
              @change="paixuChange"
              v-decorator="[
              'sortNum',
              {
                rules: [{ required: true, message: '请输入排序' }],
              },
            ]"
          ></a-input>
        </a-form-item>
        <!-- <a-form-item
          label="父级关系"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
        >
          <a-cascader
            :options="options"
            placeholder="请选择父级关系"
            @change="onChange"
            v-decorator="[
              'Address',
              {
                rules: [{ required: true, message: '请选择父级关系' }],
              },
            ]"
          />
        </a-form-item> -->

        <div>
          <a-button
              type="primary"
              class="marginBtn"
              @click="AddInviteConfigAction"
          >确定
          </a-button
          >
          <a-button @click="$router.go(-1)" class="marginBtn">返回</a-button>
        </div>
      </a-form>
    </a-card>
  </div>
</template>

<script>
import * as API from "../../api/SetCategory";
import {mapState} from "vuex";
import editor from "../../commonComponents/editor/editor";
import address from "../../utils/cascader";
import {prefix, imgUrl} from '@/utils/env-setup'

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}

export default {
  name: "inviteConfig",
  data() {
    return {
      prefix,
      imgUrl,
      loading: false,
      categoryImage: "",
      // Info: {},
      address: {},
      rolesList: ["旗舰店", "专卖店", "自营店"],
      options: [
        {value: "ONE", label: "一级"},
        {value: "TWO", label: "二级"},
        {value: "THREE", label: "三级"},
      ],
      form: this.$form.createForm(this),
      num: 0,
      id: null,
      parentId: null,
      categoryLevel: null,
      loading: false,
      postUserData: {},
      agentLevelList: [
        {value: "ONE", label: "一级"},
        {value: "TWO", label: "二级"},
        {value: "THREE", label: "三级"},
      ],
      rewardTypeList: [
        {value: "SJ_JL", label: "升级奖励"},
        {value: "YJ_JL", label: "佣金奖励"},
      ],
      previewVisible: false,
      previewImage: "",
      fileList: [],
      previewVisibleIos: false,
      previewImageIos: "",
      fileListIos: [],
      url: "",
    };
  },
  components: {
    editor,
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
    ...mapState({
      token: (state) => state.user.token
    }),
  },
  mounted() {
    // this.merchantInfo();
  },
  created() {
    this.id = this.$route.query.id || null;
    this.parentId = this.$route.query.parentId || null;
    this.categoryLevel = this.$route.query.categoryLevel || null;
    // console.log(this.parentId, "sssssssssssss");
    // this.id ? this.getMrechDetailList() : this.idCreate();
    // console.log(address, "address");
    // this.options = address;
    this.categoryPageList()
    this.categoryInfo()

  },

  activated() {
  },
  methods: {


    categoryPageList() {
      //  let  options = [
      //    { value: "ONE", label: "一级" },
      //   { value: "TWO", label: "二级" },
      //   { value: "THREE", label: "三级" },
      // ],
      this.loading = true
      // 获取菜单信息
      API.categoryPage(this.pagination)
          .then(res => {
            if (res.code === 200) {
              let optionsValue = [{value: 0, label: "一级"}]
              this.options = res.data.length === 0 ? optionsValue : res.data;
              console.log(this.options, "sssssssssssssssssssssssssssss")
            }
            this.loading = false
          })
    },
    //图片上传
    handleChange(info) {
      console.log(info)
      if (info.file.status === "uploading") {
        this.loading = true;
        return;
      }
      if (info.file && (info.file.status === 'done')) {
        this.postUserData.categoryImage = info.file ? info.file.response.data.path : ''
        this.loading = false;
        // this.updateSubmit()
      }
      // if (info.file.status === "done") {
      //   // Get this url from response in real world.
      //   getBase64(info.file.originFileObj, (categoryImage) => {
      //     this.categoryImage = categoryImage;
      //     this.loading = false;
      //   });
      // }
    },
    //图片上传
    beforeUpload(file) {
      const isJpgOrPng =
          file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.error("You can only upload JPG file!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("Image must smaller than 2MB!");
      }
      return isJpgOrPng && isLt2M;
    },
    setFields(submitData) {
      console.log(submitData, "ddddddddddddd");
      let arr = [];
      // arr.push(submitData.provinceCode);
      // arr.push(submitData.cityCode);
      // arr.push(submitData.areaCode);
      arr.push(submitData.id)
      // arr = [...submitData.provinceCode,...submitData.cityCode,...submitData.areaCode]
      // form 回写
      this.postUserData.categoryName = submitData.categoryName;
      // this.postUserData.Address = arr
      // this.postUserData.merchantContact = submitData.merchantContact;
      // this.postUserData.companyName = submitData.companyName;
      // this.postUserData.contactPhone = submitData.contactPhone;
      // this.postUserData.password = submitData.password;
      // this.postUserData.merchantType = submitData.merchantType;
      // this.postUserData.accountAddress = submitData.accountAddress;
      // this.postUserData.Address = arr;

      // debugger
      //   password  role  accountAddress
      this.form.setFieldsValue({
        // categoryName:submitData.categoryName,
        categoryName: submitData.categoryName,
        sortNum: submitData.sortNum
        // Address: arr

        // merchantName: submitData.merchantName || undefined,
        // merchantContact: submitData.merchantContact || undefined,
        // companyName: submitData.companyName || undefined,
        // contactPhone: submitData.contactPhone || undefined,
        // contactPhone: submitData.contactPhone || undefined,
        // password: submitData.password || undefined,
        // accountAddress: submitData.accountAddress || undefined,
        // merchantType: submitData.merchantType || undefined,
      });
    },
    //详情
    categoryInfo() {
      if (this.id) {
        API.categoryInfo(this.id).then((res) => {
          this.postUserData = res.data;
          this.categoryImage = res.data.categoryImage
          // this.Info.categoryString = JSON.parse(this.categoryString)
          this.setFields(res.data);
        });
      }
    },

    // onChange(value, selectedOptions) {
    //   this.postUserData.pid = value[selectedOptions.length - 1]
    //   this.postUserData.categoryString = JSON.stringify(value)
    //   console.log(this.postUserData.categoryString,"000")
    //   if(selectedOptions.length == 1){
    //       this.postUserData.categoryLevel =  "ONE"
    //   }else if(selectedOptions.length == 2){
    //       this.postUserData.categoryLevel =  "TWO"
    //   }else if(selectedOptions.length == 3){
    //      this.postUserData.categoryLevel =  "THREE"
    //   }
    //   console.log(value[selectedOptions.length - 2],"1111")
    //   console.log(value,"222")
    // },
    roleChange(value) {
      this.postUserData.merchantType = value;
      console.log(value, 5555);
      //   this.postUserData.roleId = value;
      //   this.postUserData.roles = []
      //   value.forEach(item => {
      //     let arr = item.split(',')
      //     this.postUserData.roles.push({ "id": arr[0], "name": arr[1] })
      //   })
      // this.roles.push
    },
    idCreate() {
      // API.idCreate({str: 'SH-'}).then(res => {
      //   this.postUserData.merchantNo = res.data
      // })
    },
    editorActon(editorContent) {
      // console.log(editorContent, 1111)
      this.postUserData.remark = editorContent;
    },
    // getMrechDetailList() {
    //   this.num = 0;
    //   API.getPageDetial(this.id).then((res) => {
    //     if (res.code === 200) {
    //       this.num = 9;
    //       this.postUserData = res.data;
    //       this.fileList[0] = {
    //         uid: "-1",
    //         name: "image",
    //         status: "done",
    //         url: imgUrl + res.data.azImg,
    //       };
    //       this.fileListIos[0] = {
    //         uid: "-1",
    //         name: "image",
    //         status: "done",
    //         url: imgUrl + res.data.iosImg,
    //       };
    //     }
    //   });
    // },
    AddInviteConfigAction() {
      this.form.validateFields((err) => {
        if (!err) {
          this.id ? this.edit() : this.add();
          //  this.add();
        }
      });
    },
    //新增
    add() {
      // console.log(this.postUserData)
      this.loading = true;
      this.postUserData.pid = this.parentId ? this.parentId : 0 // 新增默认父级默认传0
      this.postUserData.categoryLevel = this.categoryLevel ? this.categoryLevel : 'ONE';
      API.categoryCreate(this.postUserData)
          .then((res) => {
            if (res.code === 200) {
              // this.$message.destroy();
              this.$message.success("添加成功");
              this.$router.go(-1);
            }
            this.loading = false;
          })
          .catch(() => {
            this.loading = false;
          });
    },
    //修改
    edit() {
      this.loading = true;
      console.log(this.postUserData, "sssssssssssss")
      API.categoryPut(this.id, this.postUserData)
          .then((res) => {
            if (res.code === 200) {
              this.$message.success("修改成功");
              this.$router.go(-1);
            }
            this.loading = false;
          })
          .catch(() => {
            this.loading = false;
          });
    },
    filterOption(input, option) {
      console.log(input, option);
      return (
          option.componentOptions.children[0].text
              .toLowerCase()
              .indexOf(input.toLowerCase()) >= 0
      );
    },
    // handleCancel() {
    //   this.previewVisible = false;
    // },
    // async handlePreview(file) {
    //   if (!file.url && !file.preview) {
    //     file.preview = await getBase64(file.originFileObj);
    //   }
    //   this.previewImage = file.url || file.preview;
    //   this.previewVisible = true;
    // },
    // handleChange({ fileList }) {
    //   this.fileList = fileList;
    //   if (fileList[0] && fileList[0].status === "done") {
    //     this.postUserData.azImg = fileList[0] ? fileList[0].response.data : "";
    //   }
    // },
    // handleCancelIos() {
    //   this.previewVisibleIos = false;
    // },
    // async handlePreviewIos(file) {
    //   if (!file.url && !file.preview) {
    //     file.preview = await getBase64(file.originFileObj);
    //   }
    //   this.previewImageIos = file.url || file.preview;
    //   this.previewVisibleIos = true;
    // },
    // handleChangeIos({ fileList }) {
    //   this.fileListIos = fileList;
    //   if (fileList[0] && fileList[0].status === "done") {
    //     this.postUserData.iosImg = fileList[0] ? fileList[0].response.data : "";
    //   }
    // },
    //表单参数
    categoryNameChange(e) {
      console.log(e.target.value)
      this.postUserData.categoryName = e.target.value;
    },
    paixuChange(e) {
      this.postUserData.sortNum = parseInt(e.target.value);

    }
    // merchantContactChange(e) {
    //   this.postUserData.merchantContact = e.target.value;
    // },
    // companyNameChange(e) {
    //   this.postUserData.companyName = e.target.value;
    // },
    // contactPhoneChange(e) {
    //   this.postUserData.contactPhone = e.target.value;
    // },
    // passwordChange(e) {
    //   this.postUserData.password = e.target.value;
    // },
    // accountAddressChange(e) {
    //   this.postUserData.accountAddress = e.target.value;
    // },
    // inviteCodeChange(e) {
    //   this.postUserData.inviteCode = e.target.value;
    // },
    // merchantNameChange(e) {
    //   this.postUserData.merchantName = e.target.value;
    // },
    // merchantNameChange(e) {
    //   this.postUserData.merchantName = e.target.value;
    // }
  },
};
</script>

